package com.glela.controller;

import javax.servlet.http.HttpServletRequest;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.HttpRequestMethodNotSupportedException;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.context.request.NativeWebRequest;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.view.json.MappingJackson2JsonView;

import com.alibaba.fastjson.JSONObject;
import com.glela.common.exception.PlatformException;
import com.glela.platform.constant.ErrorEnum;
import com.glela.platform.model.response.ResponseBaseModel;

/**********************************************
 * <p>
 * 说明：公用Controller处理类
 * </p>
 * 
 * @author liujinlei
 * @date 2015年8月1日 下午6:27:33
 * @version 2.0.1 <br/>
 **********************************************
 */
@ControllerAdvice
public class ControllerExceptionHandler {
	private static final Logger LOGGER = LoggerFactory.getLogger(ControllerExceptionHandler.class);

	/** 业务异常 */
	@ExceptionHandler({ PlatformException.class })
	public ModelAndView handlePlatformException(NativeWebRequest request, PlatformException e) {
		printHttp(request, null, e.getMessage());
		return toJsonView(new ResponseBaseModel(e.getErrorEnum()));
	}

	/** 请求方法不支持 */
	@ExceptionHandler({ HttpRequestMethodNotSupportedException.class })
	public ModelAndView handleHttpRequestMethodNotSupported(NativeWebRequest request, HttpRequestMethodNotSupportedException e) {
		printHttp(request, null, "请求方法不支持/" + e.getMessage());
		return toJsonView(new ResponseBaseModel(ErrorEnum.C29911, e.getMessage()));
	}

	/** 公用异常处理 */
	@ExceptionHandler({ Throwable.class })
	public ModelAndView handleAllException(NativeWebRequest request, Exception ex) {
		printHttp(request, ex, null);
		return toJsonView(new ResponseBaseModel(ErrorEnum.C20107));
	}

	/** 转换json视图 */
	private ModelAndView toJsonView(ResponseBaseModel responseBaseModel) {
		ModelAndView mv = new ModelAndView();
		MappingJackson2JsonView mappingJackson2JsonView = new MappingJackson2JsonView();
		mappingJackson2JsonView.addStaticAttribute("code", responseBaseModel.getCode());
		mappingJackson2JsonView.addStaticAttribute("message", responseBaseModel.getMessage());
		mv.setView(mappingJackson2JsonView);
		return mv;
	}

	/** 打印异常 */
	private HttpServletRequest printHttp(NativeWebRequest request, Exception e, Object errorMsg) {
		HttpServletRequest request2 = (HttpServletRequest) request.getNativeRequest();
		String _params_json = null;
		try {
			_params_json = JSONObject.toJSONString(request2.getParameterMap());
		} catch (Exception e1) {
			LOGGER.error("请求参数转json出错：{}", e1.getMessage(), e1);
		}
		if (e == null) {
			LOGGER.error("{} 请求地址 {} {}://{}:{}{} 参数：{}", new Object[] { errorMsg, request2.getMethod(), request2.getScheme(), request2.getLocalAddr(), request2.getServerPort() + "", request2.getRequestURI(), _params_json });
		} else {
			errorMsg = errorMsg == null ? e.getMessage() : errorMsg;
			LOGGER.error("{} 请求地址 {} {}://{}:{}{} 参数：{}", new Object[] { errorMsg, request2.getMethod(), request2.getScheme(), request2.getLocalAddr(), request2.getServerPort() + "", request2.getRequestURI(), _params_json, e });
		}
		return request2;
	}
}